package cHelper

import (
	"archive/zip"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
)

// IsExistsPath 判断文件是否存在
func IsExistsPath(f string) bool {
	_, err := os.Stat(f)
	if err == nil || os.IsExist(err) {
		return true
	}

	return false
}

// IsDir 判断目录
func IsDir(f string) bool {
	fi, e := os.Stat(f)
	if e != nil {
		return false
	}
	return fi.IsDir()
}

func MkDirAll(f string, perm os.FileMode) (err error) {
	if !IsExistsPath(f) {
		err = os.MkdirAll(f, perm)
	}

	return
}

func Zip(src string, dest string, ignores ...string) error {
	dest = filepath.Clean(dest)
	err := MkDirAll(filepath.Dir(dest), 0755)
	if err != nil {
		return err
	}
	os.Remove(dest)
	zipfile, err := os.Create(dest)
	if err != nil {
		return err
	}
	defer zipfile.Close()

	archive := zip.NewWriter(zipfile)
	defer archive.Close()

	err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		pathes := strings.Split(path, string(os.PathSeparator))
		for _, ignore := range ignores {
			if InArray(pathes, ignore) {
				return nil
			}
		}

		header, err := zip.FileInfoHeader(info)
		if err != nil {
			return err
		}

		header.Name = strings.TrimPrefix(filepath.Clean(path), filepath.Clean(filepath.Dir(src)))
		header.Name = strings.TrimPrefix(header.Name, "/")
		header.Name = strings.TrimPrefix(header.Name, string(os.PathSeparator))
		header.Name = strings.ReplaceAll(header.Name, string(os.PathSeparator), "/")
		if info.IsDir() {
			header.Name += "/"
		} else {
			header.Method = zip.Deflate
		}

		writer, err := archive.CreateHeader(header)
		if err != nil {
			return err
		}

		if !info.IsDir() {
			var file *os.File
			file, err = os.Open(path)
			if err != nil {
				return err
			}
			defer file.Close()
			_, err = io.Copy(writer, file)
		}
		return err
	})

	return err
}

func TrimPath(p string) string {
	res := filepath.Clean(p)
	res = strings.TrimRight(res, "\\")
	res = strings.TrimRight(res, "/")

	return res
}

func GetCurrentDir() string {
	dir, _ := os.Getwd()
	return TrimPath(filepath.Clean(dir))
}

func BuildPath(path string) string {
	if !filepath.IsAbs(path) {
		current, _ := os.Getwd()
		current = strings.TrimSuffix(current, string(os.PathSeparator))
		path = filepath.Clean(path)
		path = strings.TrimPrefix(path, string(os.PathSeparator))
		path = fmt.Sprintf("%s%s%s", current, string(os.PathSeparator), path)
	}

	return path
}
